<template>
  <div class="userControl">
    <!-- 用户管理页面 -->
    <!-- 新增按钮 -->
    <el-button type="primary" style="padding: 5px 20px" @click="handleAddUser">新建用户</el-button>
    <!-- 用户列表 -->
    <div class="tableData">
      <el-table :data="tableData" style="width: 100%;margin-bottom: 40px">
        <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
        <el-table-column align="center" prop="sv_d_user_name" label="姓名"></el-table-column>
        <el-table-column align="center" prop="sv_d_role_name" label="角色"></el-table-column>
        <el-table-column align="center" min-width="120" prop="sv_d_user_account_no" label="账号"></el-table-column>
        <el-table-column align="center" min-width="120" prop="sv_d_user_mobile" label="手机"></el-table-column>
        <el-table-column
          align="center"
          min-width="160"
          prop="sv_d_user_lastlogin"
          :formatter="dateFormat"
          label="最近一次登录"
        ></el-table-column>
        <el-table-column
          align="center"
          min-width="160"
          prop="sv_creation_date"
          :formatter="dateFormat"
          label="创建时间"
        ></el-table-column>
        <!-- :formatter="dateFormat" -->
        <el-table-column align="center" label="启用状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.sv_enabled" @change="handleToggle(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="150" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              style="padding: 3px 8px"
              @click="handleChangeUser(scope.row)"
            >修改</el-button>
            <el-button type="danger" style="padding: 3px 8px" @click="handleDele(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 这个是分页器 -->
    <Pagination
      :total="total"
      :pageIndex="pageIndex"
      :pageSize="pageSize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    ></Pagination>
    <!-- 弹出框 -->
    <div class="recallDetail" v-show="visible">
      <div class="content" style="width: 500px">
        <h3 class="title" style="font-size: 16px;margin-bottom: 20px">{{operateTitle}}</h3>
        <div class="close" @click="visible = false">
          <i class="fa fa-times" aria-hidden="true"></i>
        </div>
        <el-col :offset="4">
          <el-form label-width="80px" :model="formLabelAlign">
            <el-form-item style="width: 60%" size="mini" label="姓名">
              <el-input v-model="formLabelAlign.sv_d_user_name"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="登录账号">
              <el-input v-model="formLabelAlign.sv_d_user_account_no"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="登录密码">
              <el-input v-model="formLabelAlign.sv_d_user_pwd" show-password></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="用户角色">
              <el-select v-model="formLabelAlign.sv_d_role_id" placeholder="请选择">
                <el-option
                  v-for="(item, index) in roleData"
                  :key="index"
                  :label="item.sv_d_role_name"
                  :value="item.sv_d_role_id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="手机">
              <el-input v-model="formLabelAlign.sv_d_user_mobile"></el-input>
            </el-form-item>
            <el-form-item style="width: 60%" size="mini" label="状态">
              <el-switch @change="handleToggle(formLabelAlign)" v-model="formLabelAlign.sv_enabled"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="changeUser">确定</el-button>
              <el-button size="mini" @click="visible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </div>
    </div>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 这里是角色的数据
      roleData: [],
      // 这个是弹出框里的数据
      formLabelAlign: {
        sv_d_user_name: "",
        sv_d_role_id: "",
        sv_d_user_account_no: "",
        sv_d_user_pwd: "",
        sv_d_user_mobile: "",
        sv_enabled: true
      },
      visible: false,
      // 弹框中操作的标题
      operateTitle: "",
      // 分页器的数据
      total: 0, // 总条数
      pageIndex: 1, // 当前页
      pageSize: 10, // 每页数量
      // 令牌
      myToken: ""
    };
  },
  components: {
    Pagination
  },
  methods: {
    // 获取用户列表
    getOrderData() {
      this.$api
        .getStaffList(this.pageIndex, this.pageSize, this.myToken)
        .then(res => {
          const { dataList, total } = res.values;
          if (res.succeed) {
            this.total = total;
            if (dataList) {
              this.tableData = dataList.map(v => {
                return {
                  ...v
                };
              });
            }
          }
        });
    },
    //时间格式化
    dateFormat: function(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return this.$moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 分页器的方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getOrderData();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getOrderData();
    },
    // 新增操作
    handleAddUser() {
      this.visible = true;
      this.operateTitle = "新增用户";
      // 重置表单
      this.formLabelAlign = {
        sv_d_user_name: "",
        sv_d_role_id: "",
        sv_d_user_account_no: "",
        sv_d_user_pwd: "",
        sv_d_user_mobile: "",
        sv_enabled: true
      };
    },
    // 修改用户
    handleChangeUser(row) {
      this.visible = true;
      this.formLabelAlign = row;
      this.operateTitle = "修改用户";
    },
    // 新建或者修改用户
    changeUser() {
      // 检测账户是否被使用
      this.$api
        .testAccountWhetherExist(
          this.formLabelAlign.sv_d_user_account_no,
          this.myToken
        )
        .then(res => {
          if (res.succeed) {
            this.$message.error("账号已存在");
          } else {
            // 正则验证表单
            // 验证特殊字符
            const patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
            // 验证数字字母和特殊字符
            const pwdPatrn = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,}$/;
            // 姓名
            if (this.formLabelAlign.sv_d_user_name === "") {
              this.$message.error("请输入姓名");
              return;
            } else if (this.formLabelAlign.sv_d_user_name.length > 8) {
              this.$message.error("姓名长度不得超过8字符");
              return;
            } else if (patrn.test(this.formLabelAlign.sv_d_user_name)) {
              this.$message.error("请勿输入特殊字符");
              return;
            }
            // 登录账号
            if (!/^\d{4,11}$/.test(this.formLabelAlign.sv_d_user_account_no)) {
              this.$message.error("登录账号格式错误");
              return;
            }
            // 密码
            if (!pwdPatrn.test(this.formLabelAlign.sv_d_user_pwd)) {
              this.$message.error("密码格式错误");
              return;
            }
            // 角色
            if (this.formLabelAlign.sv_d_role_id == "") {
              this.$message.error("请选择用户");
              return;
            }
            // 手机号
            if (
              !/^[0,1,6,8][013456789]\d{8,9}$/.test(
                this.formLabelAlign.sv_d_user_mobile
              )
            ) {
              this.$message.error("请输入正确的手机号");
              return;
            }
            this.handleTestAccount(this.formLabelAlign.sv_d_user_account_no);
            this.$api
              .handleStaffInfo(this.formLabelAlign, this.myToken)
              .then(res => {
                if (res.succeed) {
                  this.$message({
                    type: "success",
                    message: "操作成功"
                  });
                  this.getOrderData();
                } else {
                  this.$message.error("操作失败");
                }
              });
            this.visible = false;
          }
        });
    },
    // 检测账号
    handleTestAccount(val) {
      // 检测账户是否被使用
      this.$api.testAccountWhetherExist(val, this.myToken).then(res => {
        if (res.succeed) {
          this.$message.error("账号已存在");
          this.formLabelAlign.sv_d_user_account_no = "";
        }
      });
    },
    // 改变账户状态
    handleToggle(val) {
      this.$api
        .changeAccountStatus(val.sv_d_user_id, val.sv_enabled, this.myToken)
        .then(res => {
          this.$message({
            type: "success",
            message: "操作成功"
          });
        });
    },
    // 删除用户
    handleDele(val) {
      this.$api.deleteAccount(val.sv_d_user_id, this.myToken).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        });
        this.getOrderData();
      });
    }
  },
  mounted() {
    // 获取令牌
    this.myToken = sessionStorage.getItem("myToken");
    // 获取用户列表
    this.getOrderData();
    // 角色查询
    this.$api.getRoleList(this.pageIndex, 50, this.myToken).then(res => {
      const { dataList, total } = res;
      this.total = total;
      if (dataList) {
        this.roleData = dataList.map(v => {
          return {
            ...v
          };
        });
      }
    });
  }
};
</script>

<style lang="less" scoped>
@deep: ~">>>";
.userControl {
  background-color: #fff;
  padding: 20px;
  height: -webkit-fill-available;
  // 表格
  .tableData {
    margin-top: 20px;
  }
  // 表格表头
  .tableData @{deep} .el-table th {
    background-color: #fafafa;
    color: #252525;
    font-weight: 100;
  }
  // 弹出框的样式
  .recallDetail {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    .content {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      padding: 10px;
      box-sizing: border-box;
      border-radius: 10px;
    }
    .close {
      position: absolute;
      top: 10px;
      right: 10px;
      cursor: pointer;
      color: #666;
      font-size: 20px;
    }
  }
  // 修改弹出框中表单内容的宽度
  .recallDetail @{deep} .el-input__inner {
    width: 200px;
  }
}
.userControl @{deep} .el-table::before {
  height: 0;
}
</style>